<template>
  <div class="user-manage">
    <CustomSearchTable
      :url="url"
      ref="searchtable"
      :columns="columns"
      :form="form"
      :xLength="1700"
      :rowSelectionSelect="rowSelectionSelect"
      :rowSelectionChange="rowSelectionChange"
      :rowSelectInvert="rowSelectInvert"
      @clearChoose="clearChoose"
    >
      <template slot="searchForm">
        <a-form layout="inline" :form="form">
          <a-form-item label="优惠券名称">
            <a-input v-decorator="['couponName']" placeholder="优惠券名称">
            </a-input>
          </a-form-item>
          <!-- 暂时隐藏   后面再订 -->
          <a-form-item label="发放方式">
            <a-select
              showSearch
              allowClear
              style="width: 150px"
              :options="couponIssueTypeList"
              v-decorator="['couponIssueType']"
              placeholder="请选择"
            >
            </a-select>
          </a-form-item>
          <a-form-item label="状态">
            <a-select
              showSearch
              allowClear
              style="width: 150px"
              :options="showStatusList"
              v-decorator="['couponStatus']"
              placeholder="请选择"
            >
            </a-select>
          </a-form-item>
        </a-form>
      </template>

      <template slot="oprationRow">
        <permission authority="coupon:add">
          <!-- -->
          <a-button
            type="primary"
            icon="plus"
            @click="jumpMarketingCouponDetail()"
            >新增</a-button
          >
          <a-button type="danger" @click="deleteRows()">删除</a-button>
          <a-button type="danger" @click="activeStopRows()">活动停止</a-button>
        </permission>
      </template>

      <template slot="lingqu" slot-scope="{ record }">
        <permission>
          <a-button type="link" @click="lingqu(record)">{{
            record.couponIssueNum
          }}</a-button>
        </permission>
      </template>

      <template slot="use" slot-scope="{ record }">
        <permission authority="">
          <a-button type="link" @click="use(record)">{{
            record.useNum
          }}</a-button>
        </permission>
      </template>

      <template slot="tableOperation" slot-scope="{ record }">
        <a-space>
          <permission
            v-if="
              record.couponType != 3 &&
              record.couponType != 4 &&
              record.couponIngStatus == '未开始'
            "
            authority="coupon:modify"
          >
            <!---->
            <span
              class="text-primary pointer"
              @click="jumpMarketingCouponDetail(record.id)"
              >编辑</span
            >
          </permission>
          <permission
            v-if="
              record.couponIngStatus == '进行中' ||
              record.couponIngStatus == '已结束' ||
              record.couponType == 3 ||
              record.couponType == 4
            "
            authority="coupon:modify"
          >
            <!---->
            <span
              class="text-primary pointer"
              @click="jumpMarketingCouponDetail(record.id, 'view')"
              >查看</span
            >
          </permission>

          <permission authority="">
            <!---->
            <span
              class="text-primary pointer"
              @click="jumpMarketingCouponDetail(record.id, 'copy')"
              >复制</span
            >
          </permission>

          <permission
            v-if="record.couponStatus == 0 && record.couponOwnWay == 1"
            authority="coupon:exchange:add"
          >
            <!---->
            <span class="text-primary pointer" @click="openInfo(record)"
              >券码列表</span
            >
          </permission>
          <permission authority="coupon:stop" v-if="record.couponStatus == 0">
            <!---->
            <span class="text-primary pointer" @click="openStop([record.id])">
              <template>活动停止</template>
              <!-- <template v-else>活动启用</template> -->
            </span>
          </permission>
          <permission v-if="record.couponStatus == 1" authority="coupon:delete">
            <a-popconfirm
              title="是否确认删除？"
              :getPopupContainer="getPopupContainer()"
              @confirm="() => deleteCoupon([record.id])"
            >
              <a href="javascript:;" class="text-danger pointer">删除</a>
            </a-popconfirm>
          </permission>
          <permission
            authority="coupon:promote"
            v-if="record.couponIngStatus == '进行中'"
          >
            <span class="text-primary pointer" @click="handleExtension(record)"
              >推广</span
            >
          </permission>
        </a-space>
      </template>
    </CustomSearchTable>
    <Extension
      :visible="showExtension"
      :id="extensionId"
      @cancel="showExtension = false"
      @submit="showExtension = false"
    ></Extension>
    <ExchangeCodeModel
      :record="currentRecord"
      @cancel="closeInfoModal"
      :visible="exchangeCodeVisible"
    />

    <couponUseCondition
      :visible="couponUseConditionvisivle"
      :record="currentRecord"
      @cancel="couponUseConditionvisivle = false"
    >
    </couponUseCondition>
  </div>
</template>
<script>
import deepCopy from "@/utils/deepCopy";
import { findDictNameByValue } from "@/utils/dict";
import CustomSearchTable from "./components/CustomSearchTable";
import { mapState } from "vuex";
import ExchangeCodeModel from "./components/ExchangeCodeModel";
import Extension from "./components/Extension";
import couponUseCondition from "./useCondition";
export default {
  name: "Role",
  components: {
    CustomSearchTable,
    ExchangeCodeModel,
    Extension,
    couponUseCondition,
  },
  data() {
    return {
      couponUseConditionvisivle: false,
      /*      couponUseConditionUrl:'',
      couponUseConditionForm: this.$form.createForm(this, { name: "table_search" }),
      couponUseConditionColumns:[],
      currentRecord: {},*/

      roleIdTypeOptions: [],
      couponIssueTypeList: [
        // {
        //   label: "全部",
        //   value: '',
        // },
        {
          label: "用户领取",
          value: 0,
        },
        {
          label: "新用户注册发放",
          value: 1,
        },
        {
          label: "消费满额发放",
          value: 2,
        },
      ],
      url: "/coupon/page",
      showStatusList: [
        {
          label: "禁用",
          value: "1",
        },
        {
          label: "启用",
          value: "0",
        },
      ],
      useGoodsList: [
        {
          label: "全部商品",
          value: 0,
        },
        {
          label: "指定商品分组可用",
          value: 1,
        },
        {
          label: "指定商品可用",
          value: 2,
        },
      ],
      infoVisible: false,
      exchangeCodeVisible: false,
      currentRecord: {},
      form: this.$form.createForm(this, { name: "table_search" }),
      columns: [
        {
          title: "优惠券名称",
          dataIndex: "couponName",
          key: "couponName",
          width: 200,
        },
        {
          title: "优惠券类型",
          dataIndex: "couponType",
          key: "couponType",
          width: 120,
          customRender: (text, record) =>
            findDictNameByValue("COUPON_TYPE", text),
        },
        {
          title: "优惠内容",
          dataIndex: "couponAmount",
          key: "couponAmount",
          width: 150,
          customRender: (value, row) => {
            if (
              row.couponType == 0 ||
              row.couponType == 1 ||
              row.couponType == 3
            ) {
              return "优惠金额" + value + "元";
            } else if (row.couponType == 2 || row.couponType == 4) {
              return "打" + row.discountRatio + "折";
            }
            return value;
          },
        },
        {
          title: "使用条件",
          dataIndex: "couponFullMoney",
          key: "couponFullMoney",
          width: 200,
          customRender: (text, row) => {
            // 1、订单满xx元可用，最多优惠xx钱（使用门槛和最多优惠都不为-1）
            // 2、无门槛，最多优惠xx钱（使用门槛为-1，最多优惠不为-1）
            // 3、订单满xx元可用（最多优惠为-1，使用门槛不为-1）
            // 4、无门槛（使用门槛为-1，最多优惠也为-1）
            if (row.couponFullMoney != -1 && row.mostDiscount != -1) {
              return `订单满${row.couponFullMoney}元可用，最多优惠${row.mostDiscount}元`;
            } else if (row.couponFullMoney == -1 && row.mostDiscount != -1) {
              return `无门槛，最多优惠${row.mostDiscount}元`;
            } else if (row.couponFullMoney != -1 && row.mostDiscount == -1) {
              return `订单满${row.couponFullMoney}元可用`;
            } else if (row.couponFullMoney == -1 && row.mostDiscount == -1) {
              return "无门槛";
            }
            return "";
            // if(row.couponType==0 || row.couponType==1){
            //   if(row.couponFullMoney!=-1){
            //     return '订单满'+text+'元可用';
            //   }
            //   return '无门槛';
            // }
            // else if(row.couponType==2){
            //   if(row.mostDiscount>0){
            //     return '最多优惠'+row.mostDiscount+'元'
            //   }
            //   return '';
            // }
            // return text;
          },
        },
        {
          title: "发放方式",
          dataIndex: "couponIssueType",
          key: "couponIssueType",
          width: 150,
          customRender: (text, row) => {
            let arr = text.split(",").map((item) => {
              return parseFloat(item);
            });
            let joinArr = [];
            if (arr.includes(0)) {
              joinArr.push("用户领取");
            }
            if (arr.includes(1)) {
              joinArr.push("新用户注册发放");
            }
            if (arr.includes(2)) {
              joinArr.push("消费满额发放");
            }
            if (arr.includes(4)) {
              joinArr.push("系统发放");
            }
            return joinArr.join("，");
            // else if(arr.includes(1) || arr.includes(2)){
            //   return '主动发放'
            // }
            // return text;
          },
        },
        {
          title: "状态",
          dataIndex: "couponStatus",
          key: "couponStatus",
          width: 100,
          customRender: (text, row) => {
            if (row.couponStatus == 0) {
              return row.couponIngStatus;
              // let currentTime = new Date().getTime();
              // if (
              //   currentTime > this.getTimestamp(row.getStartTime) &&
              //   currentTime < this.getTimestamp(row.useEndTime)
              // ) {
              //   return "进行中";
              // } else if (currentTime > this.getTimestamp(row.useEndTime)) {
              //   return "已结束";
              // } else if (currentTime < this.getTimestamp(row.getStartTime)) {
              //   return "未开始";
              // }
            } else {
              return "已结束";
            }
          },
        },
        {
          title: "领取人次",
          dataIndex: "couponIssueNum",
          key: "couponIssueNum",
          width: 100,
          scopedSlots: { customRender: "lingqu" },
        },
        {
          title: "使用人次",
          dataIndex: "useNum",
          key: "useNum",
          width: 100,
          scopedSlots: { customRender: "use" },
        },
        {
          title: "库存",
          dataIndex: "couponStocks",
          key: "couponStocks",
          width: 80,
          customRender: (text, row) => {
            if (text == -1) {
              return "不限量";
            }
            return text;
          },
        },
        {
          title: "创建时间",
          dataIndex: "createDate",
          key: "createDate",
        },
        {
          title: "失效时间",
          dataIndex: "useTimeType",
          key: "useTimeType",
          width: 160,
          customRender: (text, row) => {
            let res = "";
            if (text == 3) {
              res = "永久有效";
            } else if (text == 2) {
              res = "领券当日起" + row.receiveDaysAble + "内有效";
            } else {
              if (row.useEndTime) {
                res = row.useEndTime;
              } else {
                res = "";
              }
            }
            return res;
          },
        },
        {
          title: "操作",
          fixed: "right",
          dataIndex: "operation",
          scopedSlots: { customRender: "operation" },
        },
      ],
      showExtension: false,
      extensionId: "",
      chosenIds: [], // 不同分页下被选中的表格行id集合
      allSelectedRows: [], // 不同分页下被选中的表格行
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.userInfo || {},
    }),
  },
  created() {
    //this.$get('/coupon/page',{ids:['111','2222']})
    //this.$get('/goldenhome/gh/lottery/admin_/lottery/activity/page');
  },
  mounted() {},
  // beforeRouteEnter(to, from, next) {
  //   let isKeepAlive=(from.name=='MarketingCouponDetail' && to.query.cache==true);
  //   console.log(deepCopy(from.name),'MarketingCouponDetail', deepCopy(to.query.cache),true,isKeepAlive)
  //   to.meta.keepAlive=isKeepAlive;
  //   next();
  // },
  beforeRouteEnter(to, from, next) {
    console.log("beforeRouteEnter", to, from);
    to.meta.isBack = from.name == "MarketingCouponDetail" && !to.query.submit;
    next();
  },
  activated() {
    this.$nextTick(() => {
      console.log("activated", this.$refs);
      if (!this.$route.meta.isBack) {
        this.form.setFieldsValue({
          couponName: "",
          couponStatus: "",
        });
        this.$refs.searchtable.refreshTable();
        this.$refs.searchtable.current = 1;
        this.$refs.searchtable.pagination.current = 1;
      }
      this.$route.meta.isBack = false;
    });
  },
  methods: {
    clearChoose() {
      this.chosenIds = [];
      this.allSelectedRows = [];
    },
    // 表格单行选择
    rowSelectionSelect(record, selected) {
      if (!selected) {
        this.allSelectedRows.splice(
          this.allSelectedRows.findIndex((item) => item.id == record.id),
          1
        );
        this.chosenIds.splice(
          this.chosenIds.findIndex((item) => item == record.id),
          1
        );
      }
    },
    // 表格任意行发生选择或取消选择时回调
    rowSelectionChange(selectedRowKeys, selectedRows) {
      let _this = this;
      if (selectedRows.length > 0) {
        selectedRows.forEach((item) => {
          if (!_this.chosenIds.includes(item.id)) {
            _this.chosenIds.push(item.id);
            _this.allSelectedRows.push(item);
          }
        });
        selectedRowKeys = this.chosenIds;
        this.$refs.searchtable.selectedRowKeys = this.chosenIds;
      } else {
      }
    },
    rowSelectInvert(selected, selectedRows, changeRows) {
      if (!selected) {
        let ids = [];
        changeRows.forEach((item) => {
          ids.push(item.id);
        });
        this.chosenIds = this.chosenIds.filter(function (val) {
          return ids.indexOf(val) === -1;
        });
        let arr = [];
        this.allSelectedRows.forEach((item) => {
          if (this.chosenIds.includes(item.id)) {
            arr.push(item);
          }
        });
        this.allSelectedRows = arr;
      }
    },
    dateToTimestamp(date) {
      let d = new Date(date);
      return d.getTime();
    },
    //推广
    handleExtension(record) {
      this.extensionId = record.id;
      this.showExtension = true;
    },
    getPopupContainer() {
      return (triggerNode) => triggerNode.parentNode.parentNode;
    },
    getTimestamp(date) {
      return new Date(date).getTime();
    },

    closeInfoModal(freshTable) {
      this.exchangeCodeVisible = false;
      if (freshTable) {
        this.$refs.searchtable.handleSearch();
      }
    },
    openInfo(record) {
      this.currentRecord = record;
      this.exchangeCodeVisible = true;
    },
    // 跳转到新建微页面装修页面
    jumpMarketingCouponDetail(id = "", type) {
      let query = {
        fromType: 1,
      };
      if (id !== "") {
        query = {
          fromType: 2,
          id: id,
          current: this.$refs.searchtable.pagination.current,
          handle: type,
        };
      }
      if (id !== "" && type == "copy") {
        query = {
          fromType: 3,
          id: id,
          current: this.$refs.searchtable.pagination.current,
        };
      }
      this.$router.push({
        name: "MarketingCouponDetail",
        query,
      });
    },

    // 停止/启用
    openStop(ids) {
      // let status = record.couponStatus == 1 ? 0 : 1;
      this.$confirm({
        title: "停用提示",
        content: "确定停用优惠券？",
        okText: "确认停用",
        cancelText: "取消",
        onOk: () => {
          this.$post("/coupon/stop", { ids: ids }).then((res) => {
            if (res && res.returnCode == 1000) {
              this.$message.success("停用成功");
              this.$refs.searchtable.refreshTable();
            }
          });
        },
      });
    },
    // 删除优惠券
    deleteCoupon(ids) {
      this.$post("/coupon/delete", { ids: ids }).then((res) => {
        if (res && res.returnCode === 1000) {
          this.$message.success("删除成功");
          this.$refs.searchtable.refreshTable();
        }
      });
    },
    //多删
    deleteRows() {
      console.log(this.chosenIds);
      if (this.chosenIds.length == 0) {
        this.$message.warn("请先选择一项后再进行操作");
      } else {
        this.$confirm({
          title: "删除提示",
          content: "确定删除优惠券？",
          okText: "确认删除",
          cancelText: "取消",
          onOk: () => {
            this.$post("/coupon/delete", { ids: this.chosenIds }).then(
              (res) => {
                if (res && res.returnCode == 1000) {
                  this.$message.success("删除成功");
                  this.clearChoose();
                  this.$refs.searchtable.refreshTable();
                }
              }
            );
          },
        });
      }
    },
    //批量活动停止
    activeStopRows() {
      if (this.chosenIds.length == 0) {
        this.$message.warn("请先选择一项后再进行操作");
      } else {
        this.$confirm({
          title: "停用提示",
          content: "确定停用优惠券？",
          okText: "确认停用",
          cancelText: "取消",
          onOk: () => {
            this.$post("/coupon/stop", { ids: this.chosenIds }).then((res) => {
              if (res && res.returnCode == 1000) {
                this.$message.success("停用成功");
                this.clearChoose();
                this.$refs.searchtable.refreshTable();
              }
            });
          },
        });
      }
    },
    lingqu(record) {
      console.log(record);
      this.currentRecord = deepCopy(record);
      this.currentRecord.couponStatus = null;

      this.couponUseConditionvisivle = true;
    },
    use(record) {
      console.log(record);
      this.currentRecord = deepCopy(record);
      this.currentRecord.couponStatus = 1;
      this.couponUseConditionvisivle = true;
    },
  },
};
</script>
<style lang="less" scoped>
</style>
